//
//  AFFNavbar.m
//  AnyfishApp
//
//  Created by Bob on 14-3-10.
//  Copyright (c) 2014年 Anyfish. All rights reserved.
//

#import "AFFNavbar.h"
#import "UIImage+Blur.h"
#import "UIImage+Alpha.h"
#import "UIImage+FX.h"

static NSInteger updateCount;
static NSInteger updateSelectCount;

@implementation AFFNavButton

- (instancetype)initWithFrame:(CGRect)frame position:(AFFButtonImagePosition)position config:(NSDictionary *)config {
    self = [super initWithFrame:frame];
    if (self) {
        
        NSString *title =       [config objectForKey:kAFFBtn_Key_Title];
        BOOL isback = [[config objectForKey:kAFFBtn_Key_Is_Back] boolValue];
        
        id imgFrame = [config objectForKey:kAFFBtn_Key_Img_Frame];
        if(imgFrame){
            _frame_Image = [((NSValue*)imgFrame) CGRectValue];
        }
        
        NSObject *obj =     [config objectForKey:kAFFBtn_Key_Img_Nor];
        UIImage *img = [obj isKindOfClass:[NSString class]] ? [UIImage imageNamed:(NSString*)obj] : (UIImage*)obj;
        
        CGFloat maxWidth = imgFrame?_frame_Image.size.width: (img.size.width>frame.size.width ? frame.size.width : img.size.width);
        CGFloat maxHeight = imgFrame?_frame_Image.size.height: (img.size.height>frame.size.height ? frame.size.height : img.size.height);
        CGFloat paddingX = imgFrame?_frame_Image.origin.x : (frame.size.width-maxWidth)/2;
        CGFloat paddingY = imgFrame?_frame_Image.origin.y : (frame.size.height-maxHeight)/2;
        
        // 计算图片和lab暂用空间
        CGFloat x, y, labx, laby, labWidth, labHeight;
        
        BOOL isLeftItem = isback&&img==nil;// 说明是左边按钮没图片情况
        
        CGFloat space = 0;
        if(img){
            switch (position) {
                case EButtonImagePosition_Left: { x = -space + (isback?-space:0); y = paddingY; labx = maxWidth; laby = 0; labWidth = frame.size.width-maxWidth; labHeight = frame.size.height; } break;
                case EButtonImagePosition_Right: { x = frame.size.width-maxWidth+space; y = paddingY; labx = 0; laby = 0; labWidth = frame.size.width-maxWidth; labHeight = frame.size.height; } break;
                    
                    
                case EButtonImagePosition_Top: { x = paddingX; y = 0; labx = 0; laby = maxHeight; labWidth = frame.size.width; labHeight = frame.size.height-maxHeight; } break;
                case EButtonImagePosition_Bottom: { x = paddingX; y = frame.size.height-maxHeight; labx = 0; laby = 0; labWidth = frame.size.width; labHeight = frame.size.height-maxHeight; } break;
                    
                case EButtonImagePosition_Center: { x = paddingX; y = paddingY; labx = 0, laby = y+maxHeight; labWidth = frame.size.width; labHeight = frame.size.height-laby; } break;
                    
                default:
                    break;
            }
            
            if(imgFrame==nil){
                _frame_Image = CGRectMake(x, y, maxWidth, maxHeight);
            }
        }else {
            _frame_Label = self.bounds;
        }
        
        if(isback){
            _frame_Label = self.bounds;
            if(isLeftItem){
                _frame_Label.origin.x -= space;
            }else
                _frame_Label.origin.x = kHeight_Nav_Icon/2-space;
        }else {
            _frame_Label.origin.x += space;
        }
        
        self.imageView.contentMode = UIViewContentModeCenter;
        
        if(![NSString isNilOrEmpty:title]){
            self.titleLabel.textAlignment = isLeftItem ? kTextAlignmentLeft : (img==nil&&!isback) ? kTextAlignmentRight : NSTextAlignmentCenter;
            self.titleLabel.font = kSetting.font_NavItem;
            [self setTitle:title forState:UIControlStateNormal];
            [self setTitle:title forState:UIControlStateHighlighted];
            [self setTitle:title forState:UIControlStateSelected];
            [self setTitleColor: [UIColor colorWithARGBString:@"#1a7ffe"] forState:UIControlStateNormal];
            [self setTitleColor: [UIColor lightGrayColor] forState:UIControlStateHighlighted];
            [self setTitleColor: [UIColor lightGrayColor] forState:UIControlStateSelected];
        }
        
        [self setImage:img forState:UIControlStateNormal];
    }
    
    return self;
}

/**
 *    重写标题位置
 */
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
    return _frame_Label;
}

/**
 *    重写图片位置
 */
- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    return _frame_Image;
}

- (void)setSelected:(BOOL)selected {
    if (selected == YES) {
        self.backgroundColor = [UIColor colorWithARGBString:@"cccccc" alpha:0.5];
    }
    else {
        self.backgroundColor = [UIColor whiteColor];
    }
}

@end

@interface AFFNavbar()

@end

@implementation AFFNavbar

- (void)drawRect:(CGRect)rect {

    // 背景色
    CGRect imgRect = CGRectMake(0, 0, rect.size.width, rect.size.height-0.8);
        if(_bgColor){
            [[UIImage imageWithColor:_bgColor frame:rect] drawInRect:rect];
        }else {
            [[UIImage imageWithColorString:_bgColorStr frame:rect] drawInRect:imgRect];
        }
    
    // 底部线条
    CGRect lineRect = CGRectMake(0, rect.size.height-0.8, rect.size.width,0.8);
    [[UIImage imageWithColor:RGB(235,235,235) frame:rect] drawInRect:lineRect];
}

- (void)setBgColorStr:(NSString *)bgColorStr {
    _bgColorStr = bgColorStr;
    [self setNeedsDisplay];
}

- (void)setBgColor:(UIColor *)bgColor {
    _bgColor = bgColor;
    [self setNeedsDisplay];
}

/**
 * 通过touch来细调响应范围，控制导航响应下移，增强左右边界点击响应
 */
//- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
//    float maxY = 0, maxX = 0;
//    UIView *view = nil;
//    for (UITouch *touch in touches) {
//        float touchY = [touch locationInView:self].y;
//        if (touchY > maxY) {
//            view = touch.view;
//            maxY = touchY;
//            maxX = [touch locationInView:self].x;
//        }
//    }
//    
//    if(view){
//        CGFloat delta = 5; // 减少误差
//        CGRect fingerRect = CGRectMake(maxX-delta, maxY-delta, 10, 10);
//        
//        for(UIView *v in view.subviews){
//            if([v isKindOfClass:[UIButton class]]){
//                CGRect frame = v.frame;
//                CGRect region = [v convertRect:frame toView:self];
//                region.origin.y = region.origin.y>5?5:region.origin.y;
//                
//                if(CGRectIntersectsRect(fingerRect, region)){
//                    [v becomeFirstResponder];
//                    [((UIButton*)v) sendActionsForControlEvents:[((UIButton*)v) allControlEvents]];
//                    break;
//                }
//            }
//        }
//    }
//    
//    if (maxY < 35 )
//        [super touchesEnded:touches withEvent:event];
//    else
//        [self touchesCancelled:touches withEvent:event];
//}

@end

static char const *kDataText = "dataText";
static char const *kWithLoading = "loading";
static char const *kTxtView = "txtView";
static char const *kItems = "kItems";
static char const *kBlock = "kBlock";
static char const *kLeftItem = "kLeftItem";
static char const *kRightItem = "kRightItem";

@implementation UINavigationItem(CustomBarButtonItem)

- (AFFDataText*)dataText {
    return objc_getAssociatedObject(self, kDataText);
}

- (void)setDataText:(AFFDataText *)dataText {
    objc_setAssociatedObject(self, kDataText, dataText, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (AFFRichTextView*)txtTitle {
    return objc_getAssociatedObject(self, kTxtView);
}

- (void)setTxtTitle:(AFFRichTextView *)txtTitle {
    objc_setAssociatedObject(self, kTxtView, txtTitle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSMutableArray*)arrItems {
    return objc_getAssociatedObject(self, kItems);
}

- (void)setArrItems:(NSMutableArray *)arrItems {
    objc_setAssociatedObject(self, kItems, arrItems, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIBarButtonItem*)leftItem {
    return objc_getAssociatedObject(self, kLeftItem);
}

- (void)setLeftItem:(UIBarButtonItem *)leftItem {
    objc_setAssociatedObject(self, kLeftItem, leftItem, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIBarButtonItem*)rightItem {
    return objc_getAssociatedObject(self, kRightItem);
}

- (void)setRightItem:(UIBarButtonItem *)rightItem {
    objc_setAssociatedObject(self, kRightItem, rightItem, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (SelectedBlock)block {
    return objc_getAssociatedObject(self, kBlock);
}

- (void)setBlock:(SelectedBlock)block {
    objc_setAssociatedObject(self, kBlock , block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)isLoading {
    return [objc_getAssociatedObject(self, kWithLoading) boolValue];
}

- (void)setIsLoading:(BOOL)isLoading {
    objc_setAssociatedObject(self, kWithLoading, @(isLoading), OBJC_ASSOCIATION_ASSIGN);
}

- (void)setLoading:(BOOL)start{
    self.isLoading = start;
    
    UIActivityIndicatorView *loadView = (UIActivityIndicatorView*)[self.titleView viewWithTag:99902];
    if(loadView){
        if(start){
            [loadView startAnimating];
        }else{
            [loadView stopAnimating];
        }
    }
    
    if(start){
        loadView.hidden = NO;
    }else{
        [UIView animateWithDuration:0.5
                              delay:0.5
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             loadView.hidden = YES;
                         } completion:nil];
    }
}

- (void)setNewTitleConfig {
    UIInterfaceOrientation ota = [[UIApplication sharedApplication] statusBarOrientation];
    
    CGFloat itemTitleWidth = SCREEN_WIDTH;
    CGFloat leftWitdh = 0, rightWidth = 0;
    if(self.leftBarButtonItem.customView){
        if(leftWitdh<CGRectGetWidth(self.leftBarButtonItem.customView.frame))
            leftWitdh = CGRectGetWidth(self.leftBarButtonItem.customView.frame);
    }
    
    if(self.rightBarButtonItem.customView){
        if(rightWidth<CGRectGetWidth(self.rightBarButtonItem.customView.frame))
            rightWidth = CGRectGetWidth(self.rightBarButtonItem.customView.frame);
    }
    
    itemTitleWidth -= (leftWitdh>rightWidth?leftWitdh:rightWidth)*2/* 确保左右按钮宽度对称 */+ (SCREEN_WIDTH>=SCREEN_WIDTH?60:40)/* 导航栏左右margin20+标题左右margin20 */;
    
    if(itemTitleWidth!=self.dataText.widthSupport)
        [AFFRichTextView sizeOfAFFDataText:self.dataText widthSupport:itemTitleWidth];
    
    CGSize size = CGSizeMake(self.dataText.widthUsed, self.dataText.heightUsed);
    CGFloat x = (itemTitleWidth - size.width)/2;
    
    AFFRichTextView *txt = self.txtTitle;
    if(txt){
        CGRect frame = txt.rFrame;
        frame.origin.x = x;
        frame.origin.y = (ItemHeight-size.height)/2;
        frame.size.width = size.width;
        txt.rFrame = frame;
        [txt redrawViewWithAFFDataText:self.dataText];
    }
    
    UIActivityIndicatorView *loadView = (UIActivityIndicatorView*)[self.titleView viewWithTag:99902];
    if(loadView){
        CGRect frame = loadView.frame;
        frame.origin.x = x-ItemLoadWidth-5;
        loadView.frame = frame;
    }
}

- (void)setNewTitle:(NSString *)title{
    [self setNewTitle:title withLoadView:self.isLoading];
}

- (void)setNewTitle:(NSString *)title delay:(BOOL)delay {
    [self setNewTitle:title withLoadView:self.isLoading delay:delay];
}

- (void)setNewTitleWithDataText:(AFFDataText *)dataText {
    [self setNewTitleDataText:dataText withLoadView:self.isLoading];
}

- (void)setNewTitle:(NSString *)title withLoadView:(BOOL)withLoadView {
    AFFDataText *dataText = [[AFFDataText alloc] initWithText:title];
    [self setNewTitleDataText:dataText withLoadView:withLoadView];
}

- (void)setNewTitle:(NSString *)title withLoadView:(BOOL)withLoadView delay:(BOOL)delay {
    AFFDataText *dataText = [[AFFDataText alloc] initWithText:title];
    [self setNewTitleDataText:dataText withLoadView:withLoadView delay:delay];
}

- (void)setNewTitleDataText:(AFFDataText *)dataText withLoadView:(BOOL)withLoadView{
    [self setNewTitleDataText:dataText withLoadView:withLoadView delay:NO]; ///修改过
}

- (void)setNewTitleDataText:(AFFDataText *)dataText withLoadView:(BOOL)withLoadView delay:(BOOL)delay{
    self.dataText = [AFFDataText initWithDataText:dataText];
    self.dataText.textAlignment = kTextAlignmentCenter;
    self.dataText.font = kSetting.font_Title_Big;
    self.dataText.color = kSetting.color_NavTitle;
    self.isLoading = withLoadView;
    
    if(self.titleView && delay){

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSInteger count = 1;
            if(count==updateCount)
                [self setNewTitleDelay];
        });

    }else {
        [self setNewTitleDelay];
    }
}

- (void)setNewTitleDelay {
    updateCount ++;
    
    if(self.titleView){
        for(UIView *v in self.titleView.subviews){
            [v removeFromSuperview];
        }
    }
    
    // 这里必须根据导航栏左右控件宽度计算导航栏宽度，当左右控件发生变化时必须触发标题重绘
    CGFloat itemTitleWidth = SCREEN_WIDTH;
    CGFloat leftWitdh = 0, rightWidth = 0;
    if(self.leftBarButtonItem.customView){
        if(leftWitdh<CGRectGetWidth(self.leftBarButtonItem.customView.frame))
            leftWitdh = CGRectGetWidth(self.leftBarButtonItem.customView.frame);
    }
    
    if(self.rightBarButtonItem.customView){
        if(rightWidth<CGRectGetWidth(self.rightBarButtonItem.customView.frame))
            rightWidth = CGRectGetWidth(self.rightBarButtonItem.customView.frame);
    }
    
    itemTitleWidth -= (leftWitdh>rightWidth?leftWitdh:rightWidth)*2/* 确保左右按钮宽度对称 */+ (isPad?80:(ScreenScale>2?60:50))/* 导航栏左右margin20+标题左右margin20 */;
    
    if(!self.dataText.hadAnalyzed)
        [AFFRichTextView sizeOfAFFDataText:self.dataText widthSupport:itemTitleWidth];
    
    CGSize size = CGSizeMake(self.dataText.widthUsed, self.dataText.heightUsed);
    CGFloat x = (itemTitleWidth - size.width)/2;
    
    // title为空时显示在中间
    CGRect frame = CGRectMake(x-ItemLoadWidth-5, 7,ItemLoadWidth, ItemLoadWidth);
    UIActivityIndicatorView *loadView = nil;
    // 默认支持转
    loadView = [[UIActivityIndicatorView alloc] initWithFrame:frame];
    loadView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    loadView.hidden = YES;
    loadView.tag = 99902;
    
    if([self.dataText isEmpty]){
        loadView.center = CGPointMake(itemTitleWidth/2, 15);
    }
    
    AFFRichTextView *txt = self.txtTitle ? self.txtTitle : [[AFFRichTextView alloc] initWithAFFDataText:nil
                                                                 target:self
                                                                  frame:CGRectMake(x, (ItemHeight-size.height)/2, size.width, 0)];
    
    txt.rFrame = CGRectMake(x, (ItemHeight-size.height)/2, size.width, 0);
    txt.adjustFontToFitOneline = YES;
    txt.font = kSetting.font_Title_Big;
    txt.textColor = kSetting.color_NavTitle;
    txt.isAutoPullRefuse = YES;
    self.txtTitle = txt;
    
    [txt redrawViewWithAFFDataText:self.dataText];
    if(self.dataText.needPullText){
        __weak typeof(self) weakSelf = self;
        [self.dataText pullDataWithConfig:nil block:^(BOOL result, id dataText) {
            [weakSelf setNewTitleWithDataText:dataText];
        }];
    }

    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, self.titleView.frame.origin.y, itemTitleWidth, ItemHeight)];
    view.autoresizingMask = UIViewAutoresizingNone;
    view.autoresizesSubviews = YES;
    //    view.backgroundColor = [UIColor redColor];
    [view addSubview:txt];
    
    [view addSubview:loadView];
    
    
    if (iPad||iPadPro||iPadRetina) {
        [txt mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(view);
            if (iPad||iPadPro||iPadRetina) {
                make.centerX.equalTo(view).offset(-10);
            }
            make.centerX.equalTo(view);
            make.width.mas_equalTo(size.width);
            make.height.mas_equalTo(20);
        }];
    }


    
    self.titleView = view;
    self.title = [self.dataText showText];
    
    [self setLoading:self.isLoading];
}

- (void)setNewTitle:(NSString *)title tagImg:(NSString*)tagImg{
    [self setNewTitle:title withLoadView:YES];
    
    UIView *view = self.titleView;
    CGRect txtFrame = self.txtTitle.frame;
    if(![NSString isNilOrEmpty:tagImg]){
        UIImage *img = [UIImage imageWithFileName:tagImg];
        if(img){
            UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(txtFrame.origin.x + txtFrame.size.width + 2, (ItemHeight-16)/2, 16, 16)];
            imgV.image = img;
            [view addSubview:imgV];
        }
    }
}

- (void)setNewTitleCircle:(NSString *)title target:(id)target action:(SEL)action{
    [self setNewTitle:title withLoadView:YES];
    
    UIView *view = self.titleView;
    UIView *txt = self.txtTitle;
    
    // 添加三角形
    UIButton *dropDownList = [[UIButton alloc] init];
    dropDownList.frame = CGRectMake(CGRectGetMaxX(txt.frame), CGRectGetMaxY(txt.bounds)-6
                                    , 5.5, 5.5);
    [dropDownList setBackgroundImage:[UIImage imageWithFileName:@"ic_yuquan_dropdown_list_triangle"] forState:UIControlStateNormal];
    dropDownList.backgroundColor = [UIColor clearColor];
    [view addSubview:dropDownList];
    [txt addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:target action:action]];
}

- (void)setNewTitleView:(UIView *)view {
    self.titleView = view;
}

/*
    此方法内部需要实现
    1.自定义view支持点击展开一个列表（列表高度根据items数量计算，需要多高展示多高，剩余部分半透明遮挡）
    2.自定义view最好采用button，有点击效果。其子view需要使用富文本控件，（小图标可以考虑做成一个子UiImageView）
    3.选择列表采用AFFTableViewCellOneSmall，不显示头像
    4.点击cell后列表消失，回调block通知vc刷新
 */
//- (void)setNewTitleSel:(AFFData*)dataSel items:(NSArray*)items withAll:(BOOL)withAll block:(void(^)(NSObject *obj))block {
//    self.arrItems = [NSMutableArray arrayWithArray:items];
//
//    if(withAll && items.count>1){
//        AFFDataText *txt = [[AFFDataText alloc] initWithText:@"全部"];
//        [self.arrItems insertObject:txt atIndex:0];
//    }
//
//    AFFData *data = dataSel?dataSel:[self.arrItems firstObject];
////    [self updataNaviTitle:data];
//    self.block = block;
//}

- (void)setNewTitleBtnDelay {
    updateSelectCount++;
    if(self.titleView){
        for(UIView *v in self.titleView.subviews){
            [v removeFromSuperview];
        }
    }
    
    // 这里必须根据导航栏左右控件宽度计算导航栏宽度，当左右控件发生变化时必须触发标题重绘
    CGFloat itemTitleWidth = SCREEN_WIDTH;
    CGFloat leftWitdh = 0, rightWidth = 0;
    if(self.leftBarButtonItem.customView){
        if(leftWitdh<CGRectGetWidth(self.leftBarButtonItem.customView.frame))
            leftWitdh = CGRectGetWidth(self.leftBarButtonItem.customView.frame);
    }
    
    if(self.rightBarButtonItem.customView){
        if(rightWidth<CGRectGetWidth(self.rightBarButtonItem.customView.frame))
            rightWidth = CGRectGetWidth(self.rightBarButtonItem.customView.frame);
    }
    
    itemTitleWidth -= (leftWitdh>rightWidth?leftWitdh:rightWidth)*2/* 确保左右按钮宽度对称 */+ (isPad?80:(ScreenScale>2?60:40))/* 导航栏左右margin20+标题左右margin20 */;
    self.dataText.font = [UIFont fontWithSize_S:kSetting.fontSize_17];
    self.dataText.color = kSetting.color_NavTitle;
    [AFFRichTextView sizeOfAFFDataText:self.dataText widthSupport:itemTitleWidth];
    
    UIImage *imgTriangle = [UIImage imageNamed:@"ic_expense_nav_triangle"];
    
    CGSize size = CGSizeMake(self.dataText.widthUsed, self.dataText.heightUsed);
    CGFloat x = (itemTitleWidth - size.width)/2;
    
    // title为空时显示在中间
    CGRect frame = CGRectMake(x-ItemLoadWidth-5, 7,ItemLoadWidth, ItemLoadWidth);
    UIActivityIndicatorView *loadView = nil;
    // 默认支持转
    loadView = [[UIActivityIndicatorView alloc] initWithFrame:frame];
    loadView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    loadView.hidden = YES;
    loadView.tag = 99902;
    
    if([self.dataText isEmpty]){
        loadView.center = CGPointMake(itemTitleWidth/2, 15);
    }
    
    frame = CGRectMake(0, (ItemHeight-size.height)/2, size.width, 0);
    AFFRichTextView *txt = [[AFFRichTextView alloc] initWithAFFDataText:nil
                                                                                                 target:self
                                                                                                  frame:frame];
    
    txt.font = [UIFont fontWithSize_S:kSetting.fontSize_17];
    txt.rFrame = frame;
    txt.isAutoPullRefuse = YES;
    self.txtTitle = txt;
    
    [txt redrawViewWithAFFDataText:self.dataText];
    if(self.dataText.needPullText){
        __weak typeof(self) weakSelf = self;
        [self.dataText pullDataWithConfig:nil block:^(BOOL result, id dataText) {
            [weakSelf setNewTitleBtnDataText:dataText];
        }];
    }
    
    frame = CGRectMake(CGRectGetMaxX(txt.frame)+3, 0, 9, 5);
    UIImageView *bgTriangle = [[UIImageView alloc] initWithFrame:frame];
    bgTriangle.image = imgTriangle;
    bgTriangle.centerY = txt.centerY;
    bgTriangle.tag = 987655;
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, CGRectGetWidth(txt.frame)+2+CGRectGetWidth(bgTriangle.frame), ItemHeight)];
    btn.autoresizingMask = UIViewAutoresizingNone;
    btn.autoresizesSubviews = YES;
    //    view.backgroundColor = [UIColor redColor];
    [btn addSubview:txt];
    if (self.arrItems.count > 1) {
        [btn addTarget:self action:@selector(actionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn addSubview:bgTriangle];
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, self.titleView.frame.origin.y, itemTitleWidth, ItemHeight)];
    view.autoresizingMask = UIViewAutoresizingNone;
    view.autoresizesSubviews = YES;
//        view.backgroundColor = [UIColor redColor];
    [view addSubview:btn];
    [view addSubview:loadView];
    self.titleView = view;
    self.title = [self.dataText showText];
    
    [self setLoading:self.isLoading];
}

- (void)setNewTitleBtnDataText:(AFFDataText *)dataText{
    self.dataText = [AFFDataText initWithDataText:dataText];
    
    if(self.titleView){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSInteger count = 1;
            if(count==updateSelectCount)
                [self setNewTitleBtnDelay];
        });
    }else {
        [self setNewTitleBtnDelay];
    }
}

- (void)actionBtnClick:(UIButton *)sender {
    CGRect frame = [UIScreen mainScreen].bounds;
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = [UIColor clearColor];
    view.tag = 987654;
    frame = CGRectMake(0, 0, SCREEN_HEIGHT, kNavigationBar_Height+kStatusBar_Height);
    view.alpha = 0;
    UIView *viewCover = [[UIView alloc] initWithFrame:frame];
    viewCover.backgroundColor = [UIColor clearColor];
    [view addSubview:viewCover];
    
    
    UIImageView *bgTriangle = [sender viewWithTag:987655];
    [UIView animateWithDuration:0.25 animations:^{
        bgTriangle.transform = CGAffineTransformMakeRotation(M_PI);
    }];
    
    frame = CGRectMake(0, kNavigationBar_Height+kStatusBar_Height, SCREEN_WIDTH, SCREEN_HEIGHT-kNavigationBar_Height-kStatusBar_Height);
    UIView *viewContent = [[UIView alloc] initWithFrame:frame];
    viewContent.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    [view addSubview:viewContent];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissNewTitleView)];
    tap.delegate = self;
    [view addGestureRecognizer:tap];
    
    CGFloat tbvHeith = 30;// ((kHeight_Cell_S-1.75)*self.arrItems.count) > (SCREEN_HEIGHT-kNavigationBar_Height-kStatusBar_Height) ? (SCREEN_HEIGHT-kNavigationBar_Height-kStatusBar_Height) : ((kHeight_Cell_S-1.75)*self.arrItems.count);
    frame = CGRectMake(0, 0, SCREEN_WIDTH, 0);
    UITableView *tableview = [[UITableView alloc] initWithFrame:frame];
    tableview.delegate = self;
    tableview.dataSource = self;
    tableview.backgroundColor = kSetting.color_Bg_VC;
    tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableview.tag = 987656;
    [viewContent addSubview:tableview];
    [UIView animateWithDuration:0.25 animations:^{
        tableview.frame = CGRectMake(0, 0, SCREEN_WIDTH, tbvHeith);
        view.alpha = 1;
    }];
    
//    [ALERT alertWithView:view block:^(NSInteger index, BOOL isCancel) {}];
}

- (void)dismissNewTitleView{
//    UIWindow *window = [UIApplication sharedApplication].keyWindow;
//    UIView *view = [[ALERT sharedView] viewWithTag:987654];
//    UIImageView *bgTriangle = [self.titleView viewWithTag:987655];
//    UITableView *tb = [view viewWithTag:987656];
//    [UIView animateWithDuration:0.25 animations:^{
//        bgTriangle.transform = CGAffineTransformRotate(CGAffineTransformMakeRotation(-M_PI), -M_PI);
//        tb.frame = CGRectMake(0, 0, SCREEN_WIDTH, 0);
//        view.alpha=0;
//    } completion:^(BOOL finished) {
//        if(finished){
//        }
//    }];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch {
    if([NSStringFromClass([touch.view class])isEqual:@"UITableViewCellContentView"]){
        return NO;
    }
    
    return YES;
}


//- (BOOL)updataNaviTitle:(AFFData*)data {
//    AFFDataText *txt = nil;
//    if ([data isKindOfClass:[AFFDataLive class]]) {
//        AFFDataLive *temp = (AFFDataLive *)data;
//        txt = [AFFDataText initWithDataText:temp.nameLive];
//    }else if ([data isKindOfClass:[AFFDataEntity class]]) {
//        AFFDataEntity *temp = (AFFDataEntity *)data;
//        txt = [AFFDataText initWithDataText:temp.nameText];
//    }else if([data isKindOfClass:[AFFDataText class]]){
//        txt = [AFFDataText initWithDataText:(AFFDataText*)data];
//    }
//
//    if ([self.dataText.showText isEqualToString:txt.showText]) {
//        return NO;
//    }
//
//    [self setNewTitleBtnDataText:txt];
//
//    return YES;
//}

- (void)hideBarItem:(BOOL)isHide isLeft:(BOOL)isLeft {
    UIBarButtonItem *item = isLeft?self.leftBarButtonItem:self.rightBarButtonItem;
    
    if(isHide){
        if(item){
            UIView *view = [[UIView alloc] init];
            view.tag = 10990999;
            
            UIView *curView = item.customView;
            if(curView.tag!=view.tag){
                if(isLeft)
                    self.leftItem = item;
                else
                    self.rightItem = item;
            }
            
            if(isLeft)
                self.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
            else
                self.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
        }
    }else {
        if(isLeft && self.leftItem){
            self.leftBarButtonItem = self.leftItem;
        }
        
        if(!isLeft && self.rightItem){
            self.leftBarButtonItem = self.rightItem;
        }
    }
}

// ----------------------end---------------------- //
- (UIButton*)setItemWithTarget:(id)target
                   isLeft:(BOOL)isLeft
                   action:(SEL)action
                    title:(NSString *)title
                 imageNor:(NSString *)imageNor{
    // 需要点击效果－使用UIButton添加子UIButton
    // 需要控制图标位置－使用添加子View
    // 需要显示title－子View中添加显示的UILabel
    CGRect frame = CGRectMake(0, 0, ItemWidth, kNavigationBar_Height);
    // 应用最新导航图标，替换后在打开
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if(![NSString isNilOrEmpty:title]){
        [dic setObject:title forKey:kAFFBtn_Key_Title];
        if(isLeft){
            [dic setObject:[NSNumber numberWithBool:YES] forKey:kAFFBtn_Key_Is_Back];
        }
        
//        if([NSString isNilOrEmpty:imageNor]){
//            frame.size.width = ItemWidth*2;
//        }
    }
    
    if(![NSString isNilOrEmpty:imageNor])
        [dic setObject:imageNor forKey:kAFFBtn_Key_Img_Nor];
    
    AFFNavButton *btn = [[AFFNavButton alloc] initWithFrame:frame position:isLeft?EButtonImagePosition_Left:EButtonImagePosition_Right config:dic];
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    btn.tag = 10005;
    btn.tag = isLeft;
//    btn.backgroundColor = [UIColor blueColor];
    
    if(isLeft){
        self.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    else{
        self.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    
    if(self.arrItems==nil){
        if(self.dataText){
            [self setNewTitleWithDataText:self.dataText];
        }else if(![NSString isNilOrEmpty:self.title])
            [self setNewTitle:self.title];
    }
    
    return btn;
}

- (void)setItemWithView:(UIView*)view isLeft:(BOOL)isLeft{
    CGRect frame = CGRectMake(0, 0, view.frame.size.width, kNavigationBar_Height);
    view.frame = frame;
    
    if(isLeft){
        self.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
        [self.leftBarButtonItem backButtonBackgroundVerticalPositionAdjustmentForBarMetrics:UIBarMetricsDefaultPrompt];
    }
    else{
        self.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    }
    
}

- (void)setLeftPanelItemWithTarget:(id)target
                            action:(SEL)action {
    CGRect frame = CGRectMake(0, 0, ItemWidth, kNavigationBar_Height);
    // 应用最新导航图标，替换后在打开
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"ic_navi_left_entry" forKey:kAFFBtn_Key_Img_Nor];
    
    AFFNavButton *btn = [[AFFNavButton alloc] initWithFrame:frame position:EButtonImagePosition_Left config:dic];
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    btn.tag = 1;
    
    if(kAppSetting.hasNew_LeftPanel){
        // 增加红点
        UIView *tip = [[UIView alloc] initWithFrame:CGRectMake(kHeight_Nav_Icon, kBadge_Width_Notify_S*2, kBadge_Width_Notify_S, kBadge_Width_Notify_S)];
        tip.backgroundColor = kSetting.color_Badge;
        tip.layer.cornerRadius = kBadge_Width_Notify_S/2;
        tip.layer.masksToBounds = YES;
        [btn addSubview:tip];
        tip.tag = 999;
        
        // 触发动态
        [self changeAlphaAnimation:tip];
    }

    self.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)changeAlphaAnimation:(UIView*)view {
    [UIView beginAnimations:@"ChangeAlphaAnimation" context:NULL];
    [UIView setAnimationDuration:2.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [view setAlpha:view.alpha==1.0?0.2:1.0];
    [UIView setAnimationDelegate:self];
//    [UIView setAnimationRepeatCount:CGFLOAT_MAX];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:)];
    [UIView commitAnimations];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if(flag){
        UIView *view = [self.leftBarButtonItem.customView viewWithTag:999];
        [self changeAlphaAnimation:view];
    }
}

- (void)setRightItemWithTarget:(id)target
                       action1:(SEL)action1
                        image1:(NSString *)image1
                       action2:(SEL)action2
                        image2:(NSString *)image2{
    // 需要点击效果－使用UIButton添加子UIButton
    // 需要控制图标位置－使用添加子View
    // 需要显示title－子View中添加显示的UILabel
    CGFloat btnWidth = 80;
    CGRect frame = CGRectMake(0, -20, btnWidth, kNavigationBar_Height);
    
    UIView *supV = [[UIView alloc] initWithFrame:frame];
//    [supV setBackgroundColor:[UIColor blueColor]];
    
    CGFloat width = btnWidth/2;
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, (kNavigationBar_Height-width)/2, width, width)];
    [btn setImage:[UIImage imageNamed:image1] forState:UIControlStateNormal];
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0, width-kHeight_Nav_Icon, 0, 0)];
    btn.tag = 222;
    [btn addTarget:target
            action:action1 forControlEvents:UIControlEventTouchUpInside];
    
    
    frame.origin.y = 0;
    UIImage *img = [UIImage imageWithFileName:image2];
    frame.origin.x = CGRectGetMaxX(btn.frame);
    frame.size.width = btnWidth-CGRectGetWidth(btn.frame);
    // 操作按钮
    UIButton *btnSub = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnSub addTarget:target action:action2 forControlEvents:UIControlEventTouchUpInside];
    [btnSub setImage:img forState:UIControlStateNormal];
    [btnSub setImageEdgeInsets:UIEdgeInsetsMake(0, CGRectGetWidth(frame)-kHeight_Nav_Icon, 0, 0)];
    btnSub.tag = 0;
//    btnSub.backgroundColor = [UIColor redColor];
    
    btnSub.frame = frame;
    [supV addSubview:btnSub];
    
    // 调整y值，使SubView垂直居中
    [supV addSubview:btn];
    
    self.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:supV];
    
    if(self.arrItems==nil){
        if(![NSString isNilOrEmpty:self.title])
            [self setNewTitle:self.title withLoadView:YES];
    }
}

- (void)setWebLeftItemWithTarget:(id)target action:(SEL)action1 action:(SEL)action2 {
    CGRect frame = CGRectMake(0, 0, ItemWidth, kNavigationBar_Height);
    // 应用最新导航图标，替换后在打开
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"1" forKey:kAFFBtn_Key_Title];
    [dic setObject:[NSNumber numberWithBool:YES] forKey:kAFFBtn_Key_Is_Back];
    [dic setObject:[UIImage imageNamed:@"ic_navi_back"] forKey:kAFFBtn_Key_Img_Nor];
    
    AFFNavButton *btn = [[AFFNavButton alloc] initWithFrame:frame position:EButtonImagePosition_Left config:dic];
    [btn addTarget:target action:action1 forControlEvents:UIControlEventTouchUpInside];
    btn.tag = 1;
    
    //创建返回键
    UIView *supV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ItemWidth*2, kNavigationBar_Height)];
    [supV setBackgroundColor:[UIColor clearColor]];
    [supV addSubview:btn];
    
    CGFloat padding = 8;
    CGFloat width = ItemWidth-padding*2;
    frame = CGRectMake(CGRectGetWidth(frame)+padding+(ScreenScale>2?10:0), (kNavigationBar_Height-width)/2, width, width);
    // 操作按钮
    UIButton *btnSub = [[UIButton alloc] initWithFrame:frame];
//    [btnSub setTitle:@"关闭" forState:UIControlStateNormal];
//    [btnSub.titleLabel setFont:kSetting.font_9];
//    btnSub.layer.borderWidth = kSetting.height_Separate;
//    btnSub.layer.cornerRadius = width/2;
//    btnSub.layer.borderColor = kSetting.color_ffffff.CGColor;
//    [btnSub setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [btnSub setTitleColor:[UIColor colorWithWhite:0.5 alpha:1] forState:UIControlStateHighlighted];
//    [btnSub setTitleColor:[UIColor colorWithWhite:0.5 alpha:1] forState:UIControlStateSelected];
    
    [btnSub setImage:[UIImage imageNamed:@"ic_navi_close"] forState:UIControlStateNormal];
    
    [btnSub addTarget:target action:action2 forControlEvents:UIControlEventTouchUpInside];
    
    [supV addSubview:btnSub];
    
    self.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:supV];
}

- (void)setCircleBoxCount:(NSInteger)count{
    UILabel *lab = (UILabel*)[self.rightBarButtonItem.customView viewWithTag:999901];
    UIView *view = [self.rightBarButtonItem.customView viewWithTag:999902];
    if(lab){
        lab.hidden = view.hidden = count==0;
        if(count>0){
            CGRect frame = lab.frame;
            frame.size.width = count > 9 ? 21 : 14;
            lab.frame = frame;
            lab.text = count > 99 ? @"•••" : [NSString stringWithFormat:@"%d",(int)count];
        }
    }
}

- (void)setBackItemWithTarget:(id)target
                       action:(SEL)action
                        title:(NSString *)title {
    [self setItemWithTarget:target isLeft:YES action:action title:title imageNor:BackItemImage];
}

@end


